#include "Mutex.h"

#ifdef _WIN32
#include <windows.h>

Mutex::Mutex()
{ 
    //临界区的使用，而不是用Mutex 在同一进程下的同步线程操作性能更好
    this->__handle__ = new CRITICAL_SECTION;
    InitializeCriticalSection((CRITICAL_SECTION *)__handle__);
}

Mutex::~Mutex()
{
    DeleteCriticalSection((LPCRITICAL_SECTION)__handle__);
    __handle__ = nullptr;
}

void Mutex::Acquire()
{
    EnterCriticalSection((CRITICAL_SECTION *)__handle__);
}

bool Mutex::TryAcquire()
{
    return TryEnterCriticalSection((CRITICAL_SECTION *)__handle__) != FALSE;
}

void Mutex::Release()
{
    LeaveCriticalSection((CRITICAL_SECTION *)__handle__);
}

#else

#include <pthread.h>

Mutex::Mutex()
{
    pthread_mutex_t *mutex = new pthread_mutex_t;
    pthread_mutexattr_t attr;
    pthread_mutexattr_init(&attr);
    /* 可重入锁*/
    pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
    pthread_mutex_init(mutex, &attr);
    this->__handle__ = mutex;
}

Mutex::~Mutex()
{
    pthread_mutex_destroy((pthread_mutex_t *)__handle__);
    __handle__ = nullptr;
}

void Mutex::Acquire()
{
    pthread_mutex_lock((pthread_mutex_t *)__handle__);
}

bool Mutex::TryAcquire()
{
    return pthread_mutex_trylock((pthread_mutex_t *)__handle__) == 0;
}

void Mutex::Release()
{
    pthread_mutex_unlock((pthread_mutex_t *)__handle__);
}

#endif